import {
  Button,
  Modal,
  RadioButton,
  RadioGroup,
  Select,
  SelectOption,
  Space,
  Switch
} from 'ant-design-vue'
import moment from 'moment'
import { json, text } from 'stream/consumers'
import { defineComponent, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { companyApi, xhImformationApi } from '@/apis'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks/useDialog'
import { bus, copyText, optionsToMap } from '@/utils'
import { debounce } from '@/utils/throttle'

import styles from './index.module.css'

export default defineComponent({
  name: 'BasicInformation',
  setup() {
    const dataCenterModalData = ref({
      expectAmount: 0,
      totalWithdraw: 0,
      withDrawList: [],
      totalEarnings: 0
    })
    const modalId = ref()
    const sid = ref()
    const scompanyid = ref()
    const selectParentName = ref()
    const selectCompanyId = ref()
    const salesCompanyId = ref()
    const modalstatus = ref()
    const showDialog = ref(false)
    const showDialogDataCenter = ref(false)
    const dialogLoading = ref(false)
    const tableRef = ref({} as ProTableRef)
    const nameList = ref([] as any[])
    const nameList2 = ref([] as any[])
    const rejectDlgRef = ref({})
    const awaitCount = ref(0)
    const positionLevelOptions = [
      { label: '暂无', value: 0 },
      { label: '群主', value: 1 },
      { label: '副群主', value: 2 },
      { label: '预备群主', value: 3 },
      { label: '预备副群主', value: 4 },
      { label: '考核预备群主', value: 5 },
      { label: '考核预备副群主', value: 6 }
    ]
    const serviceLevel = [
      { label: '暂无', value: 0 },
      { label: '一星', value: 1 },
      { label: '二星', value: 2 },
      { label: '三星', value: 3 },
      { label: '四星', value: 4 },
      { label: '五星', value: 5 }
    ]
    const companyStatus = [
      { label: '开通中', value: 0 },
      { label: '已开通', value: 1 },
      { label: '已停业', value: 2 }
    ]
    const groupNumber = [
      { label: '1', value: 1 },
      { label: '2', value: 2 },
      { label: '3', value: 3 },
      { label: '4', value: 4 },
      { label: '5', value: 5 },
      { label: '6', value: 6 },
      { label: '7', value: 7 },
      { label: '8', value: 8 },
      { label: '9', value: 9 },
      { label: '10', value: 10 },
      { label: '11', value: 11 },
      { label: '12', value: 12 },
      { label: '13', value: 13 },
      { label: '14', value: 14 },
      { label: '15', value: 15 },
      { label: '16', value: 16 },
      { label: '17', value: 17 },
      { label: '18', value: 18 },
      { label: '19', value: 19 },
      { label: '20', value: 20 },
      { label: '21', value: 21 }
    ]
    const ceoLevel = [
      { label: '暂无', value: 0 },
      { label: '零星', value: 10 },
      { label: '一星', value: 1 },
      { label: '二星', value: 2 },
      { label: '三星', value: 3 },
      { label: '四星', value: 4 },
      { label: '五星', value: 5 }
    ]
    const serviceStatus = [
      { label: '暂无', value: 0 },
      { label: '预备', value: 1 },
      { label: '正式', value: 2 }
    ]
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        type: 'seq',
        border: true,
        align: 'center',
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '基本账号姓名',
              field: 'accountName',
              titleAlign: 'right',
              titleWidth: 100,
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入账号姓名',
                  allowClear: true
                }
              }
            },
            {
              title: '基本账号ID',
              field: 'id',
              titleAlign: 'right',
              titleWidth: 100,
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入账号ID',
                  allowClear: true
                }
              }
            },
            {
              title: '服务商星级',
              field: 'serviceProviderLevel',
              titleAlign: 'right',
              titleWidth: 100,
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: serviceLevel
              }
            },
            {
              title: '上级姓名',
              field: 'parentId',
              titleAlign: 'right',
              titleWidth: 100,
              slots: {
                default: 'parentname'
              }
            },
            {
              title: '服务商类型',
              field: 'serviceProviderType',
              titleAlign: 'right',
              titleWidth: 100,
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: serviceStatus
              }
            },
            {
              title: '战队',
              field: 'combatTeam',
              titleAlign: 'right',
              titleWidth: 100,
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入战队名称',
                  allowClear: true
                }
              }
            },
            {
              title: '登录手机号',
              field: 'mobile',
              titleAlign: 'right',
              titleWidth: 100,
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入手机号',
                  allowClear: true
                }
              }
            },
            {
              title: '销售公司名称',
              field: 'applicantMobile',
              titleAlign: 'right',
              titleWidth: 100,
              slots: {
                default: 'salescompany'
              }
            },
            {
              title: '销售公司状态',
              field: 'status',
              titleAlign: 'right',
              titleWidth: 100,
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: companyStatus
              }
            },
            {
              title: '群号',
              field: 'groupNumber',
              titleAlign: 'right',
              titleWidth: 100,
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: groupNumber
              }
            },
            {
              title: '总裁星级',
              field: 'presidentStarRating',
              titleAlign: 'right',
              titleWidth: 100,
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: ceoLevel
              }
            },
            {
              slots: {
                default: () => {
                  return (
                    <Space>
                      <Button type="primary" htmlType="submit">
                        查询
                      </Button>
                      <Button
                        htmlType="reset"
                        onClick={() => {
                          selectParentName.value = null
                          sid.value = null
                          scompanyid.value = null
                          selectCompanyId.value = null
                        }}
                      >
                        重置
                      </Button>
                    </Space>
                  )
                }
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 150,
          resizable: true
        },
        columns: [
          {
            title: '*基本账号姓名',
            field: 'accountName',
            width: 150,
            fixed: 'left'
          },
          {
            title: '*基本账号ID',
            field: 'id',
            width: 160
          },
          {
            title: '*登录手机号',
            field: 'mobile',
            width: 140
          },
          {
            title: '上级姓名',
            field: 'parentAccountName',
            width: 100
          },
          {
            title: '战队',
            field: 'combatTeam',
            width: 130
          },
          {
            title: '服务商星级',
            field: 'serviceProviderLevel',
            width: 130,
            formatter: ({ cellValue }) => {
              return optionsToMap(serviceLevel)[cellValue]
            }
          },
          {
            title: '职位',
            field: 'positionLevel',
            formatter: ({ cellValue }) => {
              return optionsToMap(positionLevelOptions)[cellValue]
            }
          },
          {
            title: '销售公司名称',
            field: 'funame',
            width: 160
          },
          {
            title: '销售公司状态',
            field: 'salesCompanyStatus',
            width: 140,
            formatter: ({ cellValue }) => {
              return optionsToMap(companyStatus)[cellValue]
            }
          },
          {
            title: '是否超名额',
            field: 'overquotaOrNot',
            width: 150
          },
          {
            title: '群号',
            field: 'groupNumber',
            width: 100
          },
          {
            title: '总裁星级',
            field: 'presidentStarRating',
            width: 100,
            formatter: ({ cellValue }) => {
              return optionsToMap(ceoLevel)[cellValue]
            }
          },
          {
            title: '服务商类型',
            field: 'serviceProviderType',
            width: 120,
            formatter: ({ cellValue }) => {
              return optionsToMap(serviceStatus)[cellValue]
            }
          },
          {
            title: '服务商资料审核',
            field: 'serviceProviderName',
            width: 150
          },
          {
            title: '账号状态',
            field: 'status',
            width: 100,
            slots: {
              default: 'operstatus'
            }
          },
          {
            title: '操作',
            field: 'action',
            width: 200,
            fixed: 'right',
            slots: {
              default: 'operation'
            }
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await xhImformationApi.getImformationList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form,
                parentId: sid.value,
                salesCompanyId: salesCompanyId.value
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    onMounted(() => {
      bus.on('refreshFormationList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })
    const route = useRoute()
    const router = useRouter()

    //新增
    function handleCreate() {
      router.push({
        name: 'EditInformation'
      })
    }

    //查看详情
    function handleDetail(item) {
      router.push({
        name: 'InformationDetail',
        query: {
          id: item.id,
          falg: 1
        }
      })
    }

    //编辑
    function handleVerify(item) {
      router.push({
        name: 'EditInformation',
        query: {
          id: item.id
        }
      })
    }

    //查看销售公司
    function checkCompany(item) {
      router.push({
        name: 'SalesCompany',
        query: {
          accountName: item.accountName,
          id: item.id
        }
      })
    }
    //编辑记录
    function checkaAtion(item) {
      router.push({
        name: 'BasicInformationRecord',
        query: {
          id: item.id
        }
      })
    }
    function selectLevel(level) {
      if (level === 0) {
        return '暂无'
      }
      if (level === 1) {
        return '群主'
      }
      if (level === 2) {
        return '副群主'
      }
      if (level === 3) {
        return '预备群主'
      }
      if (level === 4) {
        return '预备副群主'
      }
      if (level === 5) {
        return '考核预备群主'
      }
      if (level === 6) {
        return '考核预备副群主'
      }
    }
    function selcettype(type) {
      if (type === 0) {
        return '暂无'
      }
      if (type === 1) {
        return '预备'
      }
      if (type === 2) {
        return '正式'
      }
    }

    function test(item) {
      debounce(async () => {
        try {
          const namelistarr = await xhImformationApi.getParentName({
            accountName: item
          })
          nameList.value = namelistarr.dataList
        } finally {
        }
      })
    }
    function selectId(value) {
      sid.value = value
    }
    function clear() {
      nameList.value = []
    }

    function openDataCenterModal(item) {
      dataCenterModalData.value = {
        expectAmount: 0,
        totalWithdraw: 0,
        withDrawList: [],
        totalEarnings: 0
      }
      // modalId.value = item.id
      showDialogDataCenter.value = true
      Promise.all([
        xhImformationApi.getDataCenterTotalPrice(item.id),
        xhImformationApi.getWithdrawList({
          memberId: item.id,
          pageParameter: {
            currentPage: 1,
            pageSize: 99
          }
        })
      ]).then(res => {
        dataCenterModalData.value.expectAmount = res?.[0]?.expectAmount || 0
        dataCenterModalData.value.totalWithdraw = res?.[0]?.totalWithdraw || 0
        // 提现列表
        dataCenterModalData.value.withDrawList =
          res?.[1]?.dataList?.map(k => {
            return {
              ...k,
              year: k?.withdrawDate?.split('-')?.[0] || '',
              month: k?.withdrawDate?.split('-')?.[1] || ''
            }
          }) || []
        // 计算总收益
        dataCenterModalData.value.totalEarnings =
          res?.[1]?.dataList
            ?.map(k => Number(k.amount))
            ?.reduce((pre, cur) => pre + cur, 0) +
          Number(res?.[0]?.expectAmount || 0)
      })
    }
    function openmodal(item) {
      showDialog.value = true
      modalId.value = item.id
      modalstatus.value = item.status
    }

    function test2(item) {
      debounce(async () => {
        try {
          const namelistarr = await companyApi.getCompanyList({
            funame: item
          })
          nameList2.value = namelistarr.dataList
        } finally {
        }
      })
    }
    function selectId2(value) {
      salesCompanyId.value = value
    }
    function clear1() {
      sid.value = null
    }
    function clear2() {
      salesCompanyId.value = null
    }
    //用户状态改变
    async function handleUserStatusChange() {
      try {
        dialogLoading.value = true
        if (modalstatus.value === 0) {
          await xhImformationApi.froze(modalId.value)
        } else {
          await xhImformationApi.active(modalId.value)
        }
        tableRef.value.refresh()
      } finally {
        dialogLoading.value = false
        showDialog.value = false
      }
    }

    return {
      scompanyid,
      serviceLevel,
      tableRef,
      sid,
      modalId,
      dialogLoading,
      tableConfig,
      modalstatus,
      rejectDlgRef,
      awaitCount,
      selectParentName,
      selectCompanyId,
      salesCompanyId,
      showDialog,
      showDialogDataCenter,
      nameList2,
      nameList,
      dataCenterModalData,
      selcettype,
      checkaAtion,
      openmodal,
      openDataCenterModal,
      test,
      handleDetail,
      selectId,
      clear1,
      clear2,
      test2,
      selectId2,
      handleVerify,
      handleCreate,
      checkCompany,
      selectLevel,
      handleUserStatusChange
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            parentname: ({ row }) => (
              <Select
                allowClear
                filterOption={false}
                showSearch={true}
                v-model:value={this.selectParentName}
                placeholder="请输入"
                style="width: 200px"
                option-label-prop="label"
                dropdownMatchSelectWidth={false}
                onSearch={num => this.test(num)}
                onChange={this.selectId}
                onClear={this.clear1}
              >
                {this.nameList.map(v => (
                  <SelectOption value={v.id} label={v.accountName}>
                    {`${v.accountName} ${this.selectLevel(v.positionLevel)}
                      ${v.combatTeam || ''}
                      ${v.serviceProviderName || ''}
                      ${this.selcettype(v.serviceProviderType) || ''}`}
                  </SelectOption>
                ))}
              </Select>
            ),
            salescompany: ({ row }) => (
              <Select
                allowClear
                showSearch={true}
                filterOption={false}
                v-model:value={this.selectCompanyId}
                placeholder="请输入"
                style="width: 200px"
                option-label-prop="label"
                onSearch={num => this.test2(num)}
                onClear={this.clear2}
                onChange={this.selectId2}
                dropdownMatchSelectWidth={false}
              >
                {this.nameList2.map(v => (
                  <SelectOption value={v.id} label={v.funame}>
                    {v.funame}
                  </SelectOption>
                ))}
              </Select>
            ),
            operation: ({ row }) => (
              <div>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDetail(row)}
                >
                  查看详情
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleVerify(row)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.checkaAtion(row)}
                >
                  操作记录
                </Button>
                <Button
                  disabled={row.salesCompanyCount == 0}
                  type="link"
                  size="small"
                  onClick={() => this.checkCompany(row)}
                >
                  查看销售公司
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.openDataCenterModal(row)}
                >
                  数据中心
                </Button>
              </div>
            ),
            operstatus: ({ row }) => {
              return (
                <Switch
                  checked={row.status === 0}
                  checked-children="正常"
                  un-checked-children="冻结"
                  onClick={() => this.openmodal(row)}
                ></Switch>
              )
            },
            toolbarButtons: () => {
              return (
                <Space>
                  <Button
                    style={{ position: 'absolute', left: '10px', top: '0px' }}
                    type="primary"
                    onClick={this.handleCreate}
                  >
                    + 添加
                  </Button>
                </Space>
              )
            }
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showDialog}
          confirmLoading={this.dialogLoading}
          width={300}
          title={'提示'}
          onOk={() => this.handleUserStatusChange()}
        >
          <div v-show={this.modalstatus === 0}>是否冻结当前账号</div>
          <div v-show={this.modalstatus === 1}>是否启动当前账号</div>
        </Modal>

        {/*数据中心*/}
        <Modal
          v-model:visible={this.showDialogDataCenter}
          width={400}
          title={'数据中心'}
        >
          <div class={styles.mTop}>
            <div>累计收益（元）</div>
            <div class={styles.mTopNum}>
              ￥{this.dataCenterModalData.totalEarnings}
            </div>
          </div>
          <div class={styles.mMiddle}>
            <div>预估服务费：￥{this.dataCenterModalData.expectAmount}</div>
            <div>总已提现：￥{this.dataCenterModalData.totalWithdraw}</div>
          </div>
          <div class={styles.listWrap}>
            {this.dataCenterModalData.withDrawList.map((withDrawItem: any) => (
              <div style={{ marginTop: '30px' }}>
                <div style={{ fontWeight: 500 }}>
                  <span style={{ fontSize: '20px' }}>{withDrawItem.month}</span>
                  月/{withDrawItem.year}
                </div>
                <div class={styles.mItem}>
                  <div class={styles.flex}>
                    <div>结算单号：</div>
                    <div>{withDrawItem.settleNo || ''}</div>
                    <div
                      class={styles.copyText}
                      onClick={() => copyText(withDrawItem.settleNo || '')}
                    >
                      复制
                    </div>
                  </div>
                  <div class={styles.flex} style={{ marginTop: '12px' }}>
                    <div>
                      {withDrawItem.status === 7 ? '已' : '可'}提现服务费：
                    </div>
                    <div>￥{withDrawItem.amount || ''}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Modal>
      </div>
    )
  }
})
